package demo;

import javax.swing.*;
import java.awt.*;

class WindowDocument extends JFrame {
    JTextArea inputText, showText;
    JMenuBar menubar;
    JMenu menu;
    JMenuItem itemCopy, itemCut, itemPaste, itemSave, itemOpen, itemReplace, itemSum;
    TextListener textChangeListener; // inputText的监视器
    demo handleListener; // itemCopy,itemCut,itemPaste的监视器

    WindowDocument() {
        init();
        setLayout(new FlowLayout());
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    void init() {
        inputText = new JTextArea(16, 28);
        showText = new JTextArea(16, 28);
        showText.setLineWrap(true); // 文本自动回行
        showText.setWrapStyleWord(true); // 文本区以单词为界自动换行
        menubar = new JMenuBar();
        menu = new JMenu("编辑");
        itemCopy = new JMenuItem("复制(C)");
        itemCut = new JMenuItem("剪切(T)");
        itemPaste = new JMenuItem("粘贴(P)");
        itemOpen = new JMenuItem("打开(O)");
        itemSave = new JMenuItem("保存(S)");
        itemReplace = new JMenuItem("替换(T)");
        itemSum = new JMenuItem("统计(R)");
        itemCopy.setAccelerator(KeyStroke.getKeyStroke('c'));// 设置快捷方式
        itemCut.setAccelerator(KeyStroke.getKeyStroke('t'));
        itemOpen.setAccelerator(KeyStroke.getKeyStroke('o'));// 设置快捷方式
        itemSave.setAccelerator(KeyStroke.getKeyStroke('s'));
        itemReplace.setAccelerator(KeyStroke.getKeyStroke('t'));
        itemSum.setAccelerator(KeyStroke.getKeyStroke('r'));
        itemCopy.setActionCommand("copy");
        itemCut.setActionCommand("cut");
        itemPaste.setActionCommand("paste");
        itemOpen.setActionCommand("open");
        itemSave.setActionCommand("save");
        itemReplace.setActionCommand("replace");
        itemSum.setActionCommand("sum");
        menu.add(itemCopy);
        menu.add(itemCut);
        menu.add(itemPaste);
        menu.add(itemOpen);
        menu.add(itemSave);
        menu.add(itemReplace);
        menu.add(itemSum);
        menubar.add(menu);
        setJMenuBar(menubar);
        add(new JScrollPane(inputText));
        add(new JScrollPane(showText));
        textChangeListener = new TextListener();
        handleListener = new demo();
        textChangeListener.setInputText(inputText);
        textChangeListener.setShowText(showText);
        handleListener.setInputText(inputText);
        handleListener.setShowText(showText);
        (inputText.getDocument()).addDocumentListener(textChangeListener);// 向文档注册监视器
        itemCopy.addActionListener(handleListener); // 向菜单项注册监视器
        itemCut.addActionListener(handleListener);
        itemPaste.addActionListener(handleListener);
        itemOpen.addActionListener(handleListener);
        itemSave.addActionListener(handleListener);
        itemReplace.addActionListener(handleListener);
        itemSum.addActionListener(handleListener);
    }
}
